# -*- coding: utf-8 -*-

from urllib import request
import urllib
import json

from logger import logger


domain_name = 'waycloud.cn'
sub_domain_name = 'vpn'


class DnsPodOperation():
    """
    DNSPod操作类
    """

    def __init__(self):
        pass

    @staticmethod
    def get_base_data():
        return {
            'login_email': 'zzh_161@sohu.com',
            'login_password': '19870625',
            'format': 'json'
        }

    @staticmethod
    def get_json_data(url, data):
        """

        :param url:
        :type url: str
        :param data:
        :type data: dict
        :return:
        :rtype: dict
        """
        try:
            req = request.Request(url)
            opener = request.build_opener()

            data = urllib.parse.urlencode(data).encode('utf8')
            response = opener.open(req, data, timeout=5)

            result = response.read().decode('utf-8')

            return json.loads(result)
        except Exception as e:
            raise e

    def get_domain_id(self):
        url = 'https://dnsapi.cn/Domain.List'
        data = self.get_base_data()
        json_data = self.get_json_data(url, data)

        domains = json_data['domains']
        """:type : list[dict]"""
        for entry in domains:
            if entry['name'] == domain_name:
                return entry['id']

        msg = '没有找到域名为：waycloud.cn的记录！ \n' + json.dumps(domains)
        raise Exception(msg)

    def get_vpn_record(self):
        """
        获取vpn.waycloud.cn的记录
        :return:
        :rtype: str
        """
        url = 'https://dnsapi.cn/Record.List'

        domain_id = self.get_domain_id()
        data = self.get_base_data()
        data['domain_id'] = domain_id

        json_data = self.get_json_data(url, data)
        records = json_data['records']
        """:type : list[dict]"""

        vpn_recorder = [x for x in records if x['name'].lower() == sub_domain_name]

        if vpn_recorder is None:
            msg = '没有找到名为：vpn 的记录！\n' + json.dumps(records)
            raise Exception(msg)
        return vpn_recorder

    def get_vpn_record_id(self):
        vpn_recorder = self.get_vpn_record()
        result = vpn_recorder[0]['id']
        return result

    def get_vpn_record_ip(self):
        vpn_recorder = self.get_vpn_record()
        result = vpn_recorder[0]['value']
        return result

    def update_vpn_record(self, ip):
        """
        更新vpn.waycloud.cn的记录
        :param ip:
        :type ip: str
        :return:
        :rtype:
        """
        url = 'https://dnsapi.cn/Record.Modify'

        domain_id = self.get_domain_id()
        recorder_id = self.get_vpn_record_id()
        data = self.get_base_data()
        data['domain_id'] = domain_id
        data['record_id'] = recorder_id
        data['value'] = ip
        data['sub_domain'] = sub_domain_name
        data['record_type'] = 'A'
        data['record_line'] = '默认'

        json_data = self.get_json_data(url, data)

        logger.info(json_data)
        return json_data


operation = DnsPodOperation()